package com.ruoyi.web.controller.recipe;

import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import com.ruoyi.common.core.domain.entity.SysDictData;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.DictUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.recipe.domain.RecipeCategory;
import com.ruoyi.recipe.domain.RecipeDish;
import com.ruoyi.recipe.service.IRecipeDishService;
import com.ruoyi.recipe.service.impl.RecipeDishItemServiceImpl;
import com.ruoyi.system.service.ISysDictDataService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.recipe.domain.RecipeDishItem;
import com.ruoyi.recipe.service.IRecipeDishItemService;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * 材料Controller
 * 
 * @author ruoyi
 * @date 2024-11-23
 */
@Controller
@RequestMapping("/recipe/item")
public class RecipeDishItemController extends BaseController {
    private String prefix = "recipe/item";

    @Autowired
    private IRecipeDishItemService recipeDishItemService;

    @Autowired
    private IRecipeDishService recipeDishService;

    @Autowired
    private ISysDictDataService sysDictDataService;

    @RequiresPermissions("recipe:item:view")
    @GetMapping()
    public String item() {
        return prefix + "/item";
    }

    /**
     * 查询材料列表
     */
    @RequiresPermissions("recipe:item:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(RecipeDishItem recipeDishItem) {
        startPage();
        List<RecipeDishItem> list = recipeDishItemService.selectRecipeDishItemList(recipeDishItem);
        return getDataTable(list);
    }

    /**
     * 导出材料列表
     */
    @RequiresPermissions("recipe:item:export")
    @Log(title = "材料", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(RecipeDishItem recipeDishItem) {
        List<RecipeDishItem> list = recipeDishItemService.selectRecipeDishItemList(recipeDishItem);
        ExcelUtil<RecipeDishItem> util = new ExcelUtil<RecipeDishItem>(RecipeDishItem.class);
        return util.exportExcel(list, "材料数据");
    }

    /**
     * 新增材料
     */
    @GetMapping("/add/{dishId}")
    public String add(@PathVariable("dishId") Long dishId, ModelMap mmap) {
        RecipeDish recipeDish = recipeDishService.selectRecipeDishByDishId(dishId);
        mmap.put("recipeDish", recipeDish);
        return prefix + "/add";
    }

    /**
     * 新增保存材料
     */
    @RequiresPermissions("recipe:item:add")
    @Log(title = "材料", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(RecipeDishItem recipeDishItem) {
        return toAjax(recipeDishItemService.insertRecipeDishItem(recipeDishItem));
    }

    /**
     * 修改材料
     */
    @RequiresPermissions("recipe:item:edit")
    @GetMapping("/edit/{itemId}")
    public String edit(@PathVariable("itemId") Long itemId, ModelMap mmap) {
        RecipeDishItem recipeDishItem = recipeDishItemService.selectRecipeDishItemByItemId(itemId);
        mmap.put("recipeDishItem", recipeDishItem);
        return prefix + "/edit";
    }

    /**
     * 修改保存材料
     */
    @RequiresPermissions("recipe:item:edit")
    @Log(title = "材料", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(RecipeDishItem recipeDishItem) {
        return toAjax(recipeDishItemService.updateRecipeDishItem(recipeDishItem));
    }

    /**
     * 删除材料
     */
    @RequiresPermissions("recipe:item:remove")
    @Log(title = "材料", businessType = BusinessType.DELETE)
    @PostMapping("/remove")
    @ResponseBody
    public AjaxResult remove(String ids) {
        return toAjax(recipeDishItemService.deleteRecipeDishItemByItemIds(ids));
    }

    /**
     * 导入模板下载
     */
    @GetMapping("/importTemplate")
    @ResponseBody
    public AjaxResult importTemplate() {
        ExcelUtil<RecipeDishItem> util = new ExcelUtil<RecipeDishItem>(RecipeDishItem.class);
        return util.importTemplateExcel("菜品材料导入模板");
    }

    /**
     * 导入数据
     */
    @PostMapping("/importData")
    @ResponseBody
    public AjaxResult importData(MultipartFile file, boolean updateSupport) {
        try {
            ExcelUtil<RecipeDishItem> util = new ExcelUtil<RecipeDishItem>(RecipeDishItem.class);
            List<RecipeDishItem> list = util.importExcel(file.getInputStream());
            String message = importDishItem(list, updateSupport);
            return AjaxResult.success(message);
        } catch (Exception e) {
            logger.debug(e.getMessage());
            return AjaxResult.error(e.getMessage());
        }
    }

    public String importDishItem(List<RecipeDishItem> list, Boolean isUpdateSupport) throws Exception {
        if (StringUtils.isNull(list) || list.size() == 0) {
            logger.debug("导入菜品材料数据不能为空！");
            throw new Exception("导入菜品材料数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();

        List<RecipeDish> dishList = recipeDishService.selectRecipeDishList(null);
        // categoryName categoryId键值对
        Map<String, Long> dishMap = new HashMap<>();
        for (RecipeDish dish : dishList) {
            dishMap.put(dish.getDishName(), dish.getDishId());
        }

        Iterator<RecipeDishItem> iterator = list.iterator();
        while (iterator.hasNext()) {
            RecipeDishItem item = iterator.next();

            if (failureNum >= 10) {
                break;
            }

            if (StringUtils.isEmpty(item.getDishName())) {
                failureNum++;
                failureMsg.append("<br/>" + failureNum + "、菜品名称不能为空");
                iterator.remove();
                continue;
            }
            if (StringUtils.isEmpty(item.getItemName())) {
                failureNum++;
                failureMsg.append("<br/>" + failureNum + "、材料名称不能为空");
                iterator.remove();
                continue;
            }
            if (StringUtils.isNull(dishMap.get(item.getDishName()))) {
                failureNum++;
                failureMsg.append("<br/>" + failureNum + "、" + item.getDishName() + " - " + item.getItemName() + " 导入失败：未找到该菜品");
                iterator.remove();
                continue;
            }

            item.setDishId(dishMap.get(item.getDishName()));
            item.setCreateBy("");
            item.setStatus("0");
        }

        if (failureNum > 0) {
            failureMsg.insert(0, "很抱歉，导入失败！请修改文件后重试：");
            logger.debug(failureMsg.toString());
            throw new Exception(failureMsg.toString());
        }

        int rows = recipeDishItemService.batchInsertRecipeDishItem(list);

        if (rows <= 0) {
            failureMsg.insert(0, "很抱歉，导入失败：保存数据失败");
            logger.debug(failureMsg.toString());
            throw new Exception(failureMsg.toString());
        } else {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + rows + " 条");
        }
        return successMsg.toString();
    }
}
